package com.sky.controller.admin;

import com.github.pagehelper.Page;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@RequestMapping("/admin/dish")
@Api(tags = "菜品接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品列表")
    public Result<List<Dish>> selectByCategoryId(Long categoryId){
        log.info("categoryid:{}",categoryId);
        List<Dish> dishList =  dishService.selctByCategoryId(categoryId);
        return Result.success(dishList);
    }

    @PostMapping()
    @ApiOperation("新增菜品")
    public Result insertDish(@RequestBody DishDTO dishDTO){
        log.info("dishDTO:{}",dishDTO);
        dishService.insertDish(dishDTO);
        String key ="dish:"+dishDTO.getCategoryId();
        clearRedisByCategoryId(key);
        return Result.success();
    }

    private void clearRedisByCategoryId(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> selectDishPage(DishPageQueryDTO dishPageQueryDTO){
        log.info("dishPageQueryDTO:{}",dishPageQueryDTO);
        PageResult pageResult =  dishService.selectDishPage(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping()
    @ApiOperation("删除菜品")
    public Result deleteDishById(@RequestParam List<Long> ids){
        log.info("开始删除 ids:{}",ids);
        dishService.deleteDishById(ids);
        String key = "dish:*";
        clearRedisByCategoryId(key);
        return Result.success();
    }

    @GetMapping("{id}")
    @ApiOperation("菜品回显")
    public Result<DishVO> findDish(@PathVariable Long id){
        DishVO dishVO =  dishService.findByID(id);
        return Result.success(dishVO);
    }
    @PutMapping()
    @ApiOperation("菜品修改")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        dishService.updateDish(dishDTO);
        String key ="dish:"+dishDTO.getCategoryId();
        clearRedisByCategoryId(key);
        return Result.success();
    }

}
